package com.yq.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yq.wiki.domain.Ebook;
import com.yq.wiki.domain.EbookExample;
import com.yq.wiki.mapper.EbookMapper;
import com.yq.wiki.req.EbookQueryReq;
import com.yq.wiki.req.EbookSaveReq;
import com.yq.wiki.resp.EbookQueryResp;
import com.yq.wiki.resp.PageResp;
import com.yq.wiki.util.CopyUtil;
import com.yq.wiki.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.util.List;

@Service
//让spring扫描到该类
public class EbookService {
    public static final Logger LOG = LoggerFactory.getLogger(EbookService.class);

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req){
        PageHelper.startPage(req.getPage(),req.getSize());
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if(!ObjectUtils.isEmpty(req.getCategoryId2())){
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }

        List<Ebook> ebooksList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebooksList);
        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());

        List<EbookQueryResp> list = CopyUtil.copyList(ebooksList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }
    /**
     *
     * 保存
     */
    public void save(EbookSaveReq req){
        Ebook ebook = CopyUtil.copy(req,Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())){
            //新增
            ebook.setId(snowFlake.nextId()); ;
            ebookMapper.insert(ebook);
        }else {
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }

    }
    public void delete(Long id){
        ebookMapper.deleteByPrimaryKey(id);
    }

}



